package com.example.javademo.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.async.DeferredResult;

import java.util.concurrent.*;

/**
 * @author zcy
 */

@RestController
public class DeferredResultTest {

    DeferredResult<String> stringDeferredResult;
    ExecutorService executorService = Executors.newSingleThreadExecutor();


    @GetMapping("/testAsync")
    public DeferredResult<String> test() {
        stringDeferredResult = new DeferredResult<>(3600 * 10L);
        executorService.execute(()->{
            System.out.println("异步执行任务，当前线程为：" + Thread.currentThread().getName());
            try {
                TimeUnit.SECONDS.sleep(10);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            stringDeferredResult.setResult("异步线程执行完毕，当前线程为：" + Thread.currentThread().getName());
        });
        stringDeferredResult.onCompletion(()->{
            System.out.println("任务完成，执行调用，当前线程为：" + Thread.currentThread().getName());
        });
        stringDeferredResult.onTimeout(()->{
            System.out.println("任务失败，10秒超时，当前线程为：" + Thread.currentThread().getName());
        });
        System.out.println("nio线程为：" + Thread.currentThread().getName());
        return stringDeferredResult;
    }


}